
import json
import logging

from django.http import JsonResponse
from wxcloudrun.models import salaryList
from wxcloudrun.models import EmpNoVsTel
logger = logging.getLogger('log')
def salary(request, _):
    """
    获取当前计数

     `` request `` 请求对象
    """
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    try:
        if request.method == 'GET' or request.method == 'get':
            rsp = get_salary(request)
        elif request.method == 'POST' or request.method == 'post':
            rsp = update_salary(request)
        else:
            rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                                json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        rsp = JsonResponse({'code': 0, 'errorMsg': str(e)}, json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))
    return rsp



def get_salary(request):
    tel=request.GET['tel']
    date=request.GET['date']
    empno = EmpNoVsTel.objects.values('EmpNo').filter(phone=tel).first()
    if date != '1':

        crypt=salaryList.objects.values('crypt').filter(date=date,EmpNo=empno['EmpNo']).first()
        rsp = JsonResponse({'code': 0, 'date': crypt['crypt']},
                       json_dumps_params={'ensure_ascii': False})
    else:
        datelist=salaryList.objects.values('date').filter(EmpNo=empno['EmpNo']).all()
        rsp = JsonResponse({'code': 0, 'date': list(datelist)},
                           json_dumps_params={'ensure_ascii': False})
    return rsp

def update_salary(request):
    body = request.body
    body = json.loads(str(body, 'utf-8'))
    for i in body:
        b =salaryList()
        line = i
        b.EmpNo = line['EmpNo']
        b.date = line['date']
        b.crypt = line['crypt']
        b.save()
    rsp = JsonResponse({'code': 0, 'date': '传送成功'},
                       json_dumps_params={'ensure_ascii': False})

    return rsp